package cn.edu.bjfu.it.oyss.covid_19helper.ui.home;

import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import cn.edu.bjfu.it.oyss.covid_19helper.ProvincesNameActivity;
import cn.edu.bjfu.it.oyss.covid_19helper.R;
import cn.edu.bjfu.it.oyss.covid_19helper.bean.RiskLevel;
import cn.edu.bjfu.it.oyss.covid_19helper.utils.ApiService;
import cn.edu.bjfu.it.oyss.covid_19helper.utils.GlideImageLoader;
import cn.edu.bjfu.it.oyss.covid_19helper.utils.ProvincesHelper;
import com.youth.banner.Banner;
import com.youth.banner.BannerConfig;
import com.youth.banner.Transformer;
import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

import java.io.IOException;
import java.util.ArrayList;

public class HomeFragment extends Fragment {

    private TextView query;
    private TextView tips;
    private TextView isolation;
    private ListView high_risk_list;
    private ListView mode_risk_list;

    public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

        View root = inflater.inflate(R.layout.fragment_home, container, false);
        init(root);
        initBanner(root);
        query.setOnClickListener(v -> {
            Intent intent = new Intent(getActivity(), ProvincesNameActivity.class);
            startActivity(intent);
        });
//        tips.setOnClickListener(v -> {
//            Intent intent = new Intent(getActivity(), TipsActivity.class);
//            startActivity(intent);
//        });

        OkHttpClient.Builder builder = new OkHttpClient().newBuilder() ;//https://blog.csdn.net/linyaodai/article/details/78585121
        builder.addInterceptor(new Interceptor() {
            @Override
            public okhttp3.Response intercept(Chain chain) throws IOException {
                Request newRequest = chain.request().newBuilder()
                        .removeHeader("User-Agent")
                        .addHeader("User-Agent","Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:0.9.4)")
                        .build() ;
                return chain.proceed(newRequest);
            }
        }) ;
        OkHttpClient client = builder.build() ;

        Retrofit retrofit  = new Retrofit.Builder()
                .baseUrl("https://file1.dxycdn.com")
                .addConverterFactory(GsonConverterFactory.create())//
                .client(client)
                .build();

        ApiService apiService = retrofit.create(ApiService.class);
        Call<RiskLevel> RiskLevelCall = apiService.getRiskLevel();
        RiskLevelCall.enqueue(new Callback<RiskLevel>() {
                                     @Override
                                     public void onResponse(Call<RiskLevel> call, Response<RiskLevel> response) {
                                         RiskLevel riskLevel = response.body();
                                         ArrayList<RiskLevel.Data> data = riskLevel.getData();
                                         if(data.get(1)!=null) {
                                             ArrayList<RiskLevel.Data.DangerPros> midLevel = data.get(1).getDangerPros();
                                             setRiskList(midLevel, mode_risk_list,2);
                                         }if(data.get(0)!=null) {
                                             ArrayList<RiskLevel.Data.DangerPros> highLevel = data.get(0).getDangerPros();
                                             setRiskList(highLevel, high_risk_list,1);
                                         }
                                     }

                                     @Override
                                     public void onFailure(Call<RiskLevel> call, Throwable t) {

                                     }
                                 }
        );


        return root;
    }

    private void setRiskList(ArrayList<RiskLevel.Data.DangerPros> level, ListView risk_list, int riskLevel) {
        ArrayList<String> LevelProvince = new ArrayList<>();
        for (RiskLevel.Data.DangerPros dangerPros : level) {
            LevelProvince.add(dangerPros.getProvinceName());
            ProvincesHelper.getInstance(getActivity()).setRISKById(dangerPros.getProvinceId()+"0000",getActivity(),riskLevel);
        }

        BaseAdapter adapter = new ArrayAdapter<>(getActivity(),android.R.layout.simple_list_item_1,LevelProvince);
        risk_list.setAdapter(adapter);
    }
    @Override
    public void onResume() {
        super.onResume();
        ArrayList<String> LevelProvince = ProvincesHelper.getInstance(getActivity()).getProvinceNameByRiskLevel("1",getActivity());
        BaseAdapter adapter = new ArrayAdapter<>(getActivity(),android.R.layout.simple_list_item_1,LevelProvince);
        high_risk_list.setAdapter(adapter);
        ArrayList<String> LevelProvince2 = ProvincesHelper.getInstance(getActivity()).getProvinceNameByRiskLevel("2",getActivity());
        BaseAdapter adapter2 = new ArrayAdapter<>(getActivity(),android.R.layout.simple_list_item_1,LevelProvince2);
        mode_risk_list.setAdapter(adapter2);
    }


    private void init(View root) {
        query = root.findViewById(R.id.query);
        tips = root.findViewById(R.id.tips);
        isolation = root.findViewById(R.id.isolation);
        high_risk_list = root.findViewById(R.id.high_risk_list);
        mode_risk_list = root.findViewById(R.id.mode_risk_list);
    }
    private void initBanner(View v) {
        ArrayList<Integer> list = new ArrayList<>();
        list.add(R.drawable.p1);
        list.add(R.drawable.p2);
        list.add(R.drawable.p3);
        list.add(R.drawable.p4);
        //list.add(R.drawable.ncepu_5);
        Banner banner = v.findViewById(R.id.banner);
        //设置banner样式
        banner.setBannerStyle(BannerConfig.CIRCLE_INDICATOR);
        //设置指示器位置（当banner模式中有指示器时）
        banner.setIndicatorGravity(BannerConfig.CENTER);
        //设置图片加载器
        banner.setImageLoader(new GlideImageLoader());
        //设置图片集合
        banner.setImages(list);
        //设置banner动画效果
        banner.setBannerAnimation(Transformer.Default);
        //设置自动轮播，默认为true
        banner.isAutoPlay(true);
        //设置轮播时间
        banner.setDelayTime(3000);
        banner.start();
    }
}